package edu.cth.scrabbit.client.core.network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import edu.cth.scrabbit.shared.network.Statement;
import edu.cth.scrabbit.shared.network.Statement.Statement_Type;


/**
 * 
 * @author Marcus Harryson, Anders Jonsson
 * 
 */
public class ClientNetworkHandler extends Thread implements IClientNetworkHandler {

	private Socket client;
	private ObjectOutputStream outStream;
	private ObjectInputStream inStream;

	public ClientNetworkHandler(String hostname, int port) {

		try {
			client = new Socket(hostname, port); // create the clients socket
													// with the connection
													// hostname and portnumber.
			outStream = new ObjectOutputStream(client.getOutputStream());
		} catch (UnknownHostException e) {
			System.out.println("Unknown Host");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("IOException");
			e.printStackTrace();
		}

	}

	
	private void listenToSocket() {
		try {
			inStream = new ObjectInputStream(client.getInputStream());
		} catch (IOException e1) {
			System.out.println("IOException");
			e1.printStackTrace();
		}
		Statement incomingStatement;

		try {
			while ((incomingStatement = (Statement) inStream.readObject()) != null) {
				ClientProtocol.processStatement(incomingStatement);
				incomingStatement = null;
			}
		} catch (IOException e) {
			System.out.println("IOException");
			e.printStackTrace();

		} catch (ClassNotFoundException e) {
			System.out.println("Something went wrong. (ClassNotFound)");
			e.printStackTrace();
		}

	}

	
	@Override
	public void sendStatement(Statement st) {
		try {
			outStream.writeObject(st);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	@Override
	public void startPinging () {
		Pinger p = new Pinger();
		p.start();
	}

	
	@Override
	public void run() {
		listenToSocket();
	}

	public class Pinger extends Thread {
		private boolean isPingTime = false;
		private int pingInterval = 1000;
		private final Statement pingStatement = new Statement(
				Statement_Type.PING, null);

		public void run() {
			while (true) {
				isPingTime = true;
				try {
					Thread.sleep(pingInterval);
				} catch (InterruptedException e) {}
				if (isPingTime) {
					sendStatement(pingStatement);
				}
			}
		}
	}

}
